<?php
require_once "site_config.php";
require_once "ra_global.php";

$method = $_GET['method'];
// 店长积分商品兑换
if($method == "exchangeRepairmanScore"){
    $userId = $_GET['userid'];
    $selectedArray = json_decode($_GET['selectedarray'], true);
    $totalScore = $_GET['totalscore'];
    $name =  $_GET['name'];
    $phone =  $_GET['phone'];
    $address =  $_GET['address'];

    echo exchangeRepairmanScore($db, $userId, $selectedArray, $totalScore, $name, $phone, $address);
}

function exchangeRepairmanScore($db, $userId,  $selectedArray, $totalScore, $name, $phone, $address) {
    $result = array();

    $success = true;
    $db->ig2_query('BEGIN');

    // 用户可用积分不能少于本次兑换积分
    $user=$db->ig2_want('mae_user','id='.$userId);
    if (!$user || ($user['score'] - $user['used_score'] < $totalScore)) {
        $db->ig2_query('ROLLBACK');
        $result['errcode'] = 2;
        exit(json_encode($result));
    }

    // 本月已使用积分
    $stime=date('Y-m-01', strtotime(date("Y-m-d")));//当月开始时间 Y-m-d格式
    $etime=strtotime("$stime +1 month");//当月结束时间 时间戳
    $stime=strtotime($stime);//当月开始时间 时间戳
    $usedScore = $db->ig2_query_select("SELECT sum(l.num * p.need_integral) as usedScore FROM mae_shop_user_exchange_list l INNER JOIN mae_prize p ON l.prize_id = p.id WHERE l.uid = ".$userId." AND l.create_time >=".$stime." AND l.create_time < ".$etime);
    if ($usedScore && $usedScore[0]['usedScore'] && ($usedScore[0]['usedScore'] + $totalScore > 600)) {
        $db->ig2_query('ROLLBACK');
        $result['errcode'] = 1;
        return json_encode($result);
    }

    foreach($selectedArray as $selected) {
        $prizeId = $selected['id'];
        $num = $selected['num'];
        $prize = $db->ig2_want('mae_prize','id='.$prizeId);

        // 如果是虚拟物品，判断是否还有兑换码；如果是实物，判断是否还有库存
        if ($prize['is_virtual'] == 1) {
            for($i=0;$i<$num;$i++){
                $prizeVirtual=$db->ig2_want('mae_prize_virtual','prize_id='.$prize['id'].' and is_used=0');
                if (!$prizeVirtual) {
                    $db->ig2_query('ROLLBACK');
                    $result['errcode'] = 3;
                    $result['errmsg'] = "兑换券不足";
                    return json_encode($result);
                }

                // 虚拟物品设置为已用
                $success = $db->ig2_query("UPDATE mae_prize_virtual SET is_used = 1 WHERE id = ". $prizeVirtual['id']);
                if (!$success) {
                    $db->ig2_query('ROLLBACK');
                    $result['errcode'] = 9;
                    return json_encode($result);
                }

                // 插入兑换记录
                $value=array(
                    'id'			=>'',
                    'account_id'	=>16621,
                    'uid'			=>$user['id'],
                    'prize_id'		=>$prizeId,
                    'virtual_id'	=>$prizeVirtual['id'],
                    'create_time'	=>time(),
                    'is_virtual'	=>1,
                    'name' => $name,
                    'phone' => $phone,
                    'address' => $address,
                    'status'	=>0,
                    'num'	=>1,
                );
                $success=$db->ig2_insert2('mae_shop_user_exchange_list',$value);
                if (!$success) {
                    $db->ig2_query('ROLLBACK');
                    $result['errcode'] = 9;
                    return json_encode($result);
                }

                // 扣除个人积分
                $success = $db->ig2_query("UPDATE mae_user SET used_score = used_score + ".$prize['need_integral']." WHERE id = ".$userId);
                if (!$success) {
                    $db->ig2_query('ROLLBACK');
                    $result['errcode'] = 9;
                    return json_encode($result);
                }
            }
        } else {
            if ($prize['stock'] < $num) {
                $db->ig2_query('ROLLBACK');
                $result['errcode'] = 4;
                $result['errmsg'] = "库存不足";
                return json_encode($result);
            }

            // 插入兑换记录
            $value=array(
                'id'			=>'',
                'account_id'	=>16621,
                'uid'			=>$user['id'],
                'prize_id'		=>$prizeId,
                'virtual_id'	=>0,
                'create_time'	=>time(),
                'is_virtual'	=>0,
                'name' => $name,
                'phone' => $phone,
                'address' => $address,
                'status'	=>0,
                'num'	=>$num,
            );
            $success=$db->ig2_insert2('mae_shop_user_exchange_list',$value);

            if (!$success) {
                $db->ig2_query('ROLLBACK');
                $result['errcode'] = 9;
                return json_encode($result);
            }

            // 减库存
            $success = $db->ig2_query("UPDATE mae_prize SET stock = stock - ".$num." WHERE id = ".$prizeId);
            if (!$success) {
                $db->ig2_query('ROLLBACK');
                $result['errcode'] = 9;
                return json_encode($result);
            }

            // 扣除个人积分
            $success = $db->ig2_query("UPDATE mae_user SET used_score = used_score + ".$prize['need_integral']." WHERE id = ".$userId);
            if (!$success) {
                $db->ig2_query('ROLLBACK');
                $result['errcode'] = 9;
                return json_encode($result);
            }
        }
    }
    if ($success) {
        $db->ig2_query('COMMIT');
        $result['errcode'] = 0;
    } else {
        $db->ig2_query('ROLLBACK');
        $result['errcode'] = 9;
    }

    return json_encode($result);
}
?>